package org.example;

import bean.DB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/alterServlet")
public class alterServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String origin = request.getParameter("origin");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");

        if (id == null || id.isEmpty() || username == null || username.trim().isEmpty()) {
            sendResponse(response, "输入信息不完整，请重试！", "alterUser.jsp?id=" + id);
            return;
        }

        String sql = "UPDATE users SET username = ?, origin = ?, gender = ?, birthday = ?" +
                (password != null && !password.isEmpty() ? ", password = ?" : "") +
                " WHERE id = ?";
        try (Connection conn = new DB().createConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, origin);
            pstmt.setString(3, gender);
            pstmt.setString(4, birthday);

            if (password != null && !password.isEmpty()) {
                pstmt.setString(5, password); // 直接存储未加密密码
                pstmt.setInt(6, Integer.parseInt(id));
            } else {
                pstmt.setInt(5, Integer.parseInt(id));
            }

            int rows = pstmt.executeUpdate();
            if (rows > 0) {
                sendResponse(response, "修改成功！", "showUser.jsp");
            } else {
                sendResponse(response, "修改失败，请重试！", "alterUser.jsp?id=" + id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendResponse(response, "系统错误，请稍后再试！", "showUser.jsp");
        }
    }

    private void sendResponse(HttpServletResponse response, String message, String redirectUrl) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<script>alert('" + message + "'); window.location.href='" + redirectUrl + "';</script>");
    }
}
